package cn.edu.sjtu.stap.sootbranchinstr.template;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import cn.edu.sjtu.stap.sootbranchinstr.BranchRecorder;

public class TemplateMaker {
	private static List<IfTemplate> ifTemplates = new ArrayList<IfTemplate>();
	private static List<SwitchTemplate> switchTemplates = new ArrayList<SwitchTemplate>();
	private static List<PolyTemplate> polyTemplates = new ArrayList<PolyTemplate>();
	
	public static void addIfTemplate(IfTemplate it){
		ifTemplates.add(it);
	}
	
	public static void addSwitchTemplate(SwitchTemplate st){
		switchTemplates.add(st);
	}
	
	public static void addPolyTemplate(PolyTemplate pt){
		polyTemplates.add(pt);
	}
	
	public static void dumpTemplate(String itFileName, String stFileName, String ptFileName){
		File itFile = new File(itFileName);
		File stFile = new File(stFileName);
		File ptFile = new File(ptFileName);
		
		try{
			// output if templates
			PrintWriter itWriter = new PrintWriter(new BufferedWriter(new FileWriter(itFile)));
			for(IfTemplate it : ifTemplates){
				StringBuilder itBuilder = new StringBuilder();
				itBuilder.append(it.getKey());
				itBuilder.append(BranchRecorder.DATA_SEPARATOR);
				itBuilder.append(it.getTakenTarget());
				itWriter.println(itBuilder.toString());
			}
			itWriter.close();
			
			// output switch templates
			PrintWriter sWriter = new PrintWriter(new BufferedWriter(new FileWriter(stFile)));
			for(SwitchTemplate st : switchTemplates){
				StringBuilder stBuilder = new StringBuilder();
				stBuilder.append(st.getKey());
				
				List<SwitchTarget> tList = st.getTargets();
				for(SwitchTarget sTarget : tList){
					stBuilder.append(BranchRecorder.DATA_SEPARATOR);
					stBuilder.append(sTarget.getTargetIndex());
					stBuilder.append(BranchRecorder.DATA_SEPARATOR);
					stBuilder.append(sTarget.getTargetLine());
				}
				sWriter.println(stBuilder.toString());
			}
			sWriter.close();
			
			// output polymorphic call templates
			PrintWriter pWriter = new PrintWriter(new BufferedWriter(new FileWriter(ptFile)));
			for(PolyTemplate pt : polyTemplates){
				StringBuilder ptBuilder = new StringBuilder();
				ptBuilder.append(pt.getKey());
				ptBuilder.append(BranchRecorder.DATA_SEPARATOR);
				ptBuilder.append(pt.getCallType());
				
				List<String> tList = pt.getTargets();
				for(String t : tList){
					ptBuilder.append(BranchRecorder.DATA_SEPARATOR);
					ptBuilder.append(t);
				}
				pWriter.println(ptBuilder.toString());
			}
			pWriter.close();
		}catch(IOException ex){
			ex.printStackTrace();
		}
	}
}
